from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
from users.ser import *
from users.models import *


# Create your views here.


class NewsAPIView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        data = News.objects.all()
        page = Paginator(data,2)
        page_all = page.page(id)
        data_all = NewsModelSerializer(page_all,many=True)

        return Response({
            'data':data_all.data,
            'page_range':[i for i in page.page_range],
            'count':page.count
        })

    def post(self, request):
        data = NewsModelSerializer(data=request.data)
        if data.is_valid():
            data.save()
            return Response({'msg': '添加成功'})
        else:
            return Response({'msg': '添加失败'})


class AdvertisingAPIView(APIView):
    def get(self, request):
        id = request.GET.get('id')
        data = Advertising.objects.all()
        page = Paginator(data, 2)
        page_all = page.page(id)
        data_all = AdvertisingModelSerializer(page_all, many=True)

        return Response({
            'data': data_all.data,
            'page_range': [i for i in page.page_range]

        })

    def post(self, request):
        data = AdvertisingModelSerializer(data=request.data)
        if data.is_valid():
            data.save()
            return Response({'msg': '添加成功'})
        else:
            return Response({'msg': '添加失败'})
